package business.database.sqliteMaescorp

import groovy.sql.Sql
import java.util.HashMap;
import java.util.List;

/**
 * DAO para la tabla Corp
 * @author Administrador
 *
 */
public class CorpDAO {
	
	private def Sql sqlite;
	
	/**
	 * Inicializamos la clase con la instance de SQL
	 * @param sql
	 */
	public CorpDAO(Sql sql) {
		sqlite = sql;
	}
	
/**
 * Crea la tabla
 */
	public void create() {
		sqlite.execute("CREATE TABLE  IF NOT EXISTS Corp (idCorp integer primary key, corp text NOT NULL COLLATE NOCASE, UNIQUE (corp));");
	}
	
	/**
	 * Obtiene el maximo idcorp de la tabla
	 * @return
	 */
	public int maxidCorp() {
		String sqlQuery = "Select max(idcorp) as MAXID from Corp"
		def max = sqlite.firstRow(sqlQuery)
					
		int id
		if ((max != null) && (max[0] != null))
			id = max[0] + 1
		else id = 1
	}
	
	/**
	 * Inserta un corp
	 * @param idcorp
	 * @param corp
	 */
	public void insert(int idcorp, String corp) {
		sqlite.execute("insert into Corp values (${idcorp},?)", [corp]);
	}
	
	/**
	 * Obtiene el corp del idcorp
	 * @param idcorp identificador del corp
	 * @return corp
	 */
	public String select(int idcorp) {
		
		String sqlQuery = "Select corp from corp where idcorp = ${idcorp}"
		def corp = sqlite.firstRow(sqlQuery)
					
		if ((corp != null) && (corp[0] != null))
			return corp[0]
		else return null;
	}
	
	/**
	 * Itera el closure sobre el idcorp de todos los corps
	 * @param closure
	 */
	public void iterateCorp(Closure closure) {
		sqlite.eachRow("select idcorp from corp", closure);
	}
	/**
	* Borra el corp
	* @param idcorp
	*/
   public void delete(int idcorp) {
	   sqlite.execute("delete from corp where idcorp = ${idcorp}");
   }
   
	/**
	 * Obtiene el idcorp de un corp
	 * @param corp
	 * @return idcorp
	 */
	public Integer selectIdCorp(String corp) {
		
		String sqlQuery = "Select idcorp from corp where corp = ?"
		def idcorp = sqlite.firstRow(sqlQuery,[corp])
					
		if ((idcorp != null) && (idcorp[0] != null))
			return idcorp[0]
		else return null;
	}
	
	
}
